package fss

import (
	"encoding/json"
	"fmt"
)

type (
	Response[T any] struct {
		Code int    `json:"code"`
		Msg  string `json:"msg,omitempty"`
		Data T      `json:"data,omitempty"`

		Changed     int  `json:"changed,omitempty"`      // 配置项变更个数
		Result      bool `json:"result,omitempty"`       // 录像相关结果
		CountHit    int  `json:"count_hit,omitempty"`    // 筛选命中的流个数
		CountClosed int  `json:"count_closed,omitempty"` // 被关闭的流个数，可能小于count_hit
	}

	ResponseGetMp4RecordFile struct {
		Paths    []string `json:"paths"`
		RootPath string   `json:"rootPath"`
	}

	ResponseVersion struct {
		BranchName string `json:"branchName"`
		BuildTime  string `json:"buildTime"`
		CommitHash string `json:"commitHash"`
	}

	ResponseMediaPlayer struct {
		Identifier string `json:"identifier"`
		LocalIp    string `json:"local_ip"`
		LocalPort  int    `json:"local_port"`
		PeerIp     string `json:"peer_ip"`
		PeerPort   int    `json:"peer_port"`
		TypeId     int    `json:"type_id"`
	}

	ResponseAddStreamProxy struct {
		Key string `json:"key"`
	}

	Bytes[T any] []byte
)

func (r Response[T]) IsOk() bool {
	return r.Code == 0
}

func (r Response[T]) String() string {
	data, _ := json.MarshalIndent(r, "", " ")
	return string(data)
}

func (b Bytes[T]) Unmarshal() *Response[T] {
	var (
		r   = &Response[T]{Code: -1}
		err = json.Unmarshal(b, r)
	)
	if err != nil {
		r.Msg = fmt.Sprintf("请求解析(%s)失败: %s", b, err)
		return r
	}
	return r
}

func RequestRouteErr[T any](route string, err error) *Response[T] {
	return &Response[T]{Code: -1, Msg: fmt.Sprintf("请求接口(%s) 失败: %s", route, err)}
}
